package com.ruoyi.web.controller.system;

import cn.hutool.core.io.FileUtil;
import com.ruoyi.system.domain.SysFile;
import com.ruoyi.system.service.ISysFileService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.storage.StorageService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 对象存储服务
 */
@Slf4j
@RestController
@RequestMapping("/storage")
@RequiredArgsConstructor
public class StorageController extends BaseController {
    private final StorageService storageService;
    private final ISysFileService sysFileService;

    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String storageUrl = storageService.store(file.getInputStream(), originalFilename, file.getContentType());

        // 保存文件信息
        SysFile sysFile = new SysFile();
        sysFile.setName(originalFilename);
        sysFile.setUrl(storageUrl);
        sysFileService.insertSysFile(sysFile);

        return success(sysFile);
    }

    /**
     * 预览图片&下载文件
     * <p>
     * 请求地址：http://localhost:8080/common/static/{financial/afsdfasdfasdf_1547866868179.txt}
     */
    @GetMapping(value = "/static/{key:.+}")
    @ApiOperation(value = "预览图片&下载文件")
    public ResponseEntity<Resource> view(@PathVariable String key) {
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }

        String fileUrl = storageService.generateUrl(key);

        String type = FileUtil.getMimeType(fileUrl);
        MediaType mediaType = MediaType.parseMediaType(type);

        Resource file = storageService.loadAsResource(key);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok()
                .contentType(mediaType)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
                .body(file);
    }
}
